const WebSocket = require('ws')

const wss = new WebSocket.Server({ port: 8001 })

wss.gameId = 10000

wss.gameData = {}

// Broadcast to all.
wss.broadcast = function broadcast (data) {
  wss.clients.forEach(function each (client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data)
    }
  })
}

wss.on('connection', function connection (ws) {
  ws.on('message', function incoming (data) {
    let clientData = JSON.parse(data)
    switch (clientData.op) {
      case 'create_game':
        wss.createGame(ws)
        break
      case 'save_single_draw':
        wss.saveSingleDraw(ws, clientData.drawData)
        break
      case 'get_single_draw':
        wss.getSingleDraw(ws, clientData)
        break
      default:
        wss.broadcast(data)
    }
  })
})

wss.createGame = function (ws) {
  let gameId = wss.gameId++
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({op: 'game_created',gameId}))
    console.log('create a game')
  }
}

wss.saveSingleDraw = function (ws, drawData) {
  let gameId = wss.gameId++
  wss.gameData[gameId] = drawData  
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({op: 'save_single_draw_ok',gameId}))
    
  }
}

wss.getSingleDraw = function (ws, clientData) {
  let gameId = clientData.gameId;
  const gameData= wss.gameData[gameId] 
  console.log(gameId)
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({op: 'get_single_draw',gameData}))    
  }
}

